package qrcode

import (
	"gitee.com/yysf-xin/dproxy/controller/qrcode/internal"
	"gitee.com/yysf-xin/dproxy/pkg/tools"
	"github.com/go-chi/chi/v5"
	"github.com/makiuchi-d/gozxing"
	"github.com/makiuchi-d/gozxing/qrcode"
	"image/png"
	"net/http"
)

type QrGenerator struct {
	hints map[gozxing.EncodeHintType]interface{}
	qr *qrcode.QRCodeWriter
}

func NewQrGenerator() *QrGenerator {
	hints := make(map[gozxing.EncodeHintType]interface{})
	return &QrGenerator{hints,nil}
}

func (q *QrGenerator) GenGet(w http.ResponseWriter, data string,size int) {
	q.Gen(w,&internal.Param{
		Data: data,
		Size: size,
	})
}

func (q *QrGenerator) Gen(w http.ResponseWriter, p *internal.Param) {
	if p.Size < 1 {
		p.Size = 255
	}
	img,err:= q.qr.Encode(p.Data,gozxing.BarcodeFormat_QR_CODE, p.Size, p.Size, q.hints)
	if err == nil {
		err = png.Encode(w,img)
	}
	if err != nil {
		http.Error(w,err.Error(),400)
		tools.Log.Println("render qr fail",err)
	}
}

func (q *QrGenerator) InitRoute(router chi.Router) {
	ru := internal.QrGeneratorApiHandler{Base: q}
	router.Route("/qrcode", func(r chi.Router) {
		r.Post("/gen", ru.ServeGen)
		r.Get("/gen", ru.ServeGenGet)
	})
}
